package com.hisense.ovcloud.apicontrol.service;

import com.hisense.ovcloud.apicontrol.config.Constants;
import com.hisense.ovcloud.apicontrol.dto.req.ValidateReq;
import com.hisense.ovcloud.apicontrol.errors.ResForGW;
import com.hisense.ovcloud.apicontrol.errors.SystemError;
import com.hisense.ovcloud.apicontrol.tool.AES256CbcUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.LinkedHashMap;

@Service
@Slf4j
public class JHKSyncService extends BaseAGService {
    @Value("${jhk.sync.interfaces:/ac-julink-warehouse/getPublicKey}")
    private String jhkSyncInterfaces;

    @Value("${jhk.sync.appId:9790433051803659}")
    private String jhkSyncAppId;

    @Value("${jhk.sync.aesCBCKey:eeB3voh2saqu8eev0yeephieg4phaefi}")
    private String jhkAESCBCKey;

    public Mono<ResForGW> run(ValidateReq r, LinkedHashMap<String, Object> parametersMap) {
        ResForGW res = ResForGW.builder().build();
        res.setData(false);
        if (r.getMethod().equalsIgnoreCase(Constants.Method.GET)) {
            if (parametersMap.containsKey(Constants.PARAM_APPID) && parametersMap.get(Constants.PARAM_APPID).equals(jhkSyncAppId)) {
                res = setErrorResponse(res, SystemError.THIS_APPID_NOT_PERMITED);
            }
        } else {
            if (!parametersMap.isEmpty() && parametersMap.containsKey(Constants.PARAM_APPID)) {
                String appIdInReq = getFromParametersMap(parametersMap,Constants.PARAM_APPID);
                if (StringUtils.isNotEmpty(appIdInReq) && appIdInReq.equals(jhkSyncAppId)) {
                    if (requestUriNotInJHKSyncPermitInterfaces(r.getPath())) {
                        res = setErrorResponse(res, SystemError.THIS_APPID_NOT_PERMITED);
                    }else{
                        res.setData(true);
                    }
                }
            }
        }
        return Mono.just(res);
    }

    private boolean requestUriNotInJHKSyncPermitInterfaces(String uri) {
        return Arrays.stream(jhkSyncInterfaces.split(",")).noneMatch(uri::contains);
    }

    private WarehouseResponse encryptJHKSyncRes(WarehouseResponse rawRes) {
        rawRes.setData(AES256CbcUtils.encrypt256CBCWithoutIv(jhkAESCBCKey, rawRes.getData()));
        return rawRes;
    }

    @Data
    static
    class WarehouseResponse {
        private int code;
        private String errorMsg = "";
        private String data;
        private String domain;
        private String subDomain;
    }
}
